package com.mldkhn.led_controller;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.net.nsd.NsdManager.RegistrationListener;
import android.net.nsd.NsdManager.ResolveListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;

public class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {

	SharedPreferences mySharedPreferences;
	RegistrationListener mRegistrationListener;
    DiscoveryListener mDiscoveryListener;

    NsdManager mNsdManager;
    
    final String TAG = "---Networking";
    final String SERVICE_TYPE = "_led._tcp.";
	
	private static Integer SERVERPORT;
	private static String SERVER_IP;

	Thread socketThread;
	private Socket socket;
    
 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  
  // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
 PreferenceManager.getDefaultSharedPreferences(this.getActivity()).registerOnSharedPreferenceChangeListener(this);
 onSharedPreferenceChanged(PreferenceManager.getDefaultSharedPreferences(this.getActivity()),"");
 mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
 if(mySharedPreferences.getBoolean("checkbox_zeroconf", false))
 discoverService();
 }
 

 public void discoverService() {
     // Create the NsdServiceInfo object, and populate it.
     // The name is subject to change based on conflicts
     // with other services advertised on the same network.

     mNsdManager = (NsdManager) this.getActivity().getApplicationContext().getSystemService(Context.NSD_SERVICE);

     initializeDiscoveryListener();

     mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
 }

 public void initializeDiscoveryListener() {

     // Instantiate a new DiscoveryListener
     mDiscoveryListener = new NsdManager.DiscoveryListener() {

         //  Called as soon as service discovery begins.
         @Override
         public void onDiscoveryStarted(String regType) {
             Log.d(TAG , "Service discovery started");
         }

         @Override
         public void onServiceFound(NsdServiceInfo service) {
             // A service was found!  Do something with it.
             Log.d(TAG, "Service discovery success: " + service);
             if (!service.getServiceType().equals(SERVICE_TYPE)) {
                 // Service type is the string containing the protocol and
                 // transport layer for this service.
                 Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
             } else if (service.getServiceName().contains("LED-Controller")){
                 mNsdManager.resolveService(service, new ResolveListener() {

                     @Override
                     public void onServiceResolved(NsdServiceInfo serviceInfo) {
                         // TODO Auto-generated method stub
                         Log.d(TAG, "Resolving service...");
                         Integer port = serviceInfo.getPort();
                         InetAddress host = serviceInfo.getHost(); // getHost() will work now
                         String IP = host.getHostAddress();
                     	 EditTextPreference prefIP = (EditTextPreference) findPreference("edittext_ip");
                     	 EditTextPreference prefPort = (EditTextPreference) findPreference("edittext_port");
                     	 prefIP.setText(IP);
                         prefPort.setText(port.toString());                         
                     }

                     @Override
                     public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
                         // TODO Auto-generated method stub
                         Log.d(TAG, "Service resolve failed!");
                     }
                 });
             }
         }

         @Override
         public void onServiceLost(NsdServiceInfo service) {
             // When the network service is no longer available.
             // Internal bookkeeping code goes here.
             Log.e(TAG, "service lost: " + service);
         }

         @Override
         public void onDiscoveryStopped(String serviceType) {
             Log.i(TAG, "Discovery stopped: " + serviceType);
         }

         @Override
         public void onStartDiscoveryFailed(String serviceType, int errorCode) {
             Log.e(TAG, "Discovery failed: Error code: " + errorCode);
             mNsdManager.stopServiceDiscovery(this);
         }

         @Override
         public void onStopDiscoveryFailed(String serviceType, int errorCode) {
             Log.e(TAG, "Discovery failed: Error code: " + errorCode);
             mNsdManager.stopServiceDiscovery(this);
         }
     };
 }

 
 @Override
 public void onResume() {
     super.onResume();
     getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

 }

 @Override
 public void onPause() {
     getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
     super.onPause();
 }

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
	Preference prefIP = findPreference("edittext_ip");
	Preference prefPort = findPreference("edittext_port");
	if (prefIP instanceof EditTextPreference) {
        EditTextPreference etpIP = (EditTextPreference) prefIP;
        prefIP.setSummary("dummy");
        prefIP.setSummary(etpIP.getText());
        if(sharedPreferences.getBoolean("checkbox_zeroconf", false))
        	etpIP.setEnabled(false);
        else
        	etpIP.setEnabled(true);
	}
	if (prefPort instanceof EditTextPreference) {
        EditTextPreference etpPort = (EditTextPreference) prefPort;
        prefPort.setSummary("dummy");
        prefPort.setSummary(etpPort.getText());
        if(sharedPreferences.getBoolean("checkbox_zeroconf", false))
        	etpPort.setEnabled(false);
        else
        	etpPort.setEnabled(true);
	}	
	try{
		if(sharedPreferences.getBoolean("checkbox_zeroconf", false))
		discoverService();
		SERVER_IP = mySharedPreferences.getString("edittext_ip", "");
		SERVERPORT = Integer.parseInt(mySharedPreferences.getString("edittext_port", ""));
		socketThread = new Thread(new ClientThread());
		socketThread.start();
		PrintWriter out = new PrintWriter(new BufferedWriter(
				new OutputStreamWriter(socket.getOutputStream())),
				true);
		out.println("HELLO");
		socketThread.interrupt();
		socketThread = null;
		
		} 
		  catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
}

class ClientThread implements Runnable {
	
	@Override
	public void run() {
		
		try {
			InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

			socket = new Socket(serverAddr, SERVERPORT);

		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}


	}

}